package br.com.cfccultura.admin.control.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.stereotype.Component;

public class PropertyPlaceHolder extends PropertyPlaceholderConfigurer {

	private static final Logger logger = Logger.getLogger(PropertyPlaceHolder.class);
	
	private String externalLocation;	
	private Properties switchedProperties;
	private CriptoDES criptoDES;
	
		
	@Override
	protected String resolvePlaceholder(String placeholder, Properties props) {
		String value = null;
		if(getSwitchedProperties() != null) {
			value = getSwitchedProperties().getProperty(placeholder);
		} else {
			value = super.resolvePlaceholder(placeholder, props);
		}
		
		if (placeholder.endsWith("password")) {
			if(value != null && !value.equals("")) {
				value = criptoDES.decrypt(value);
			} else {
				value = "";
			}
		}
		
		if(logger.isDebugEnabled()) {
			if(placeholder.endsWith("password")) {
				logger.debug("Property-> " + placeholder + " | value-> ********* - " + value.length());
			} else {
				logger.debug("Property-> " + placeholder + " | value-> " + value);
			}
		}		
		
		return value;
	}

	private void loadProperties(String path) {
		try {
			java.io.InputStream is = new FileInputStream(path);
			Properties props = new Properties();
			props.load(is);
			setSwitchedProperties(props);
			logger.info("Log4j using external configuration ! - " + props.size() + " keys");
		} catch (IOException e) {
			
		}
	}

	protected void setSwitchedProperties(Properties switchedPropertiesArg) {
		switchedProperties = switchedPropertiesArg;
	}

	protected Properties getSwitchedProperties() {
		return switchedProperties;
	}

	public String getExternalLocation() {
		return externalLocation;
	}

	public void setExternalLocation(String externalLocation) {
		this.externalLocation = externalLocation;
		if (getExternalLocation() != null && !getExternalLocation().equals("")) {
			loadProperties(getExternalLocation());
		}
	}

	public CriptoDES getCriptoDES() {
		return criptoDES;
	}

	public void setCriptoDES(CriptoDES criptoDES) {
		this.criptoDES = criptoDES;
	}
}
